//
//  File.swift
//  
//
//  Created by rui on 2024/5/9.
//

import Foundation

public extension FileManager {
    static func documentsDir() throws -> String {
        if let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
            return path
        }
        throw NSError(domain: "Documents is null", code: -10086, userInfo: [NSLocalizedDescriptionKey: "Documents is null"])
    }
    static func preferencesDir() throws -> String {
        if let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first {
            return path
        }
        throw NSError(domain: "Preferences is null", code: -10086, userInfo: [NSLocalizedDescriptionKey: "Preferences is null"])
    }
    static func cachesDir() throws -> String {
        if let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first {
            return path
        }
        throw NSError(domain: "Caches is null", code: -10086, userInfo: [NSLocalizedDescriptionKey: "Caches is null"])
    }
    static func tmpDir() -> String {
        return NSTemporaryDirectory()
    }
    static func homeDir() -> String {
        return NSHomeDirectory()
    }
    static func fileExists(_ atPath: String) -> Bool {
        let fileManager = FileManager.default
        var pointer = ObjCBool(false)
        let exist = fileManager.fileExists(atPath: atPath, isDirectory: &pointer)
        return exist && !pointer.boolValue
    }
    static func directoryExists(_ atPath: String) -> Bool {
        let fileManager = FileManager.default
        var pointer = ObjCBool(true)
        let exist = fileManager.fileExists(atPath: atPath, isDirectory: &pointer)
        return exist && pointer.boolValue
    }

    static func delete(_ atPath: String) throws -> Bool {
        if directoryExists(atPath) {
            do {
                let fileManager = FileManager.default
                try fileManager.removeItem(atPath: atPath)
                return true
            } catch {
                throw(error)
            }
        }
        return true
    }

    static func createDirectory(_ atPath: String) throws -> Bool {
        if directoryExists(atPath) {
            return true
        }
        do {
            let fileManager = FileManager.default
            try fileManager.createDirectory(atPath: atPath, withIntermediateDirectories: true)
            return true
        } catch {
            throw(error)
        }
    }
    
}
